<?php 

	function checkPayment(){
		global $wpdb;	
		$prefix = "timetable_";


    $s = "SELECT 
      idclientcourse,
      course_id,
      client_id,
      paystatus_id,

      (SELECT user_id FROM timetable_client WHERE idclient = client_id) user_id,
      ifnull( (SELECT SUM( payment_amount ) FROM timetable_payment WHERE clientcourse_id = idclientcourse AND status = 'SUCCESS' ), 0) amount,
      (SELECT course_basecost FROM timetable_course WHERE idcourse = course_id ) basecost,
      if(    
        (ifnull( (SELECT SUM( payment_amount ) FROM timetable_payment WHERE clientcourse_id = idclientcourse AND status = 'SUCCESS' ), 0)
           /
        (SELECT course_basecost FROM timetable_course WHERE idcourse = course_id ) ) < 1,
        1, 0
      ) needpay 
    FROM 
      timetable_clientcourse cc";

	}


  function checkPaymentCourse($id){
      global $wpdb;
      $prefix = 'timetable_';

      $sqlsel = "SELECT IFNULL( (
                    SELECT SUM( payment_amount ) sum
                      FROM {$prefix}payment
                      WHERE clientcourse_id = {$id}
                      AND STATUS =  'SUCCESS' ) , 0
                  ) amount,
                  ifnull(  (SELECT course_basecost FROM {$prefix}course, {$prefix}clientcourse WHERE idcourse = course_id AND idclientcourse = {$id}) , 0) base";
      
      $res = $wpdb->get_results($sqlsel, ARRAY_A);

      //echo json_encode($res);

      $base = $res[0]['base']; 
      $amount  = $res[0]['amount'];

      if($base == 0) {
        $div = 0;
      }else{
        $div = $amount/$base;
      }
      
      $stat = (int) ( floor( $div ) + ceil( $div ) + 1 );
      if( filter_var($stat , FILTER_VALIDATE_INT) ){
          $sqlup = "UPDATE {$prefix}clientcourse SET paystatus_id = {$stat} WHERE idclientcourse = {$id}";
          $wpdb->query($sqlup);
          return true;
      }

      return false;
  }


?>



